﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using Project.Core.Api.Common.Base;
using Project.Core.Api.Controllers.Organization.Dto;
using Project.Core.Api.Controllers.System.IOrganization.Dto;
using Project.Core.Common;
using Project.Core.IServices.System;
using Project.Core.Model.System;

namespace Project.Core.Api.Controllers.System.IOrganization
{
    /// <summary>
    /// 授权Controller
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class OrganizationController : Controller
    {
        readonly IUserOrganizationService _userOrganizationService;
        readonly IMapper _mapper;

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userOrganizationService">组织机构Service</param>
        /// <param name="mapper">mapper</param>
        public OrganizationController(IUserOrganizationService userOrganizationService, IMapper mapper)
        {
            _userOrganizationService = userOrganizationService;
            _mapper = mapper;
        }
        #endregion

        #region 获取所有父级角色
        /// <summary>
        /// 获取所有父级角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetAllUserOrganization")]
        public async Task<ActionResult> GetAllUserOrganization([FromBody]OrganizationCondition Condition)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var list = await _userOrganizationService.Query(x => x.Belong == 0 && x.IsValid && (string.IsNullOrEmpty(Condition.Creater) || x.Creater == Condition.Creater));
                    var res = list.ToList().Select(x => new
                    {
                        _id = x.Id,
                        Belong = x.Belong,
                        CreateTime = x.CreateTime,
                        DeleteTime = x.DeleteTime,
                        IsValid = x.IsValid,
                        Remark = x.Remark,
                        OrganizationCode = x.OrganizationCode,
                        OrganizationName = x.OrganizationName,
                        Creater = x.Creater,
                        Children = _userOrganizationService.Query(k => k.Belong == x.Id && k.IsValid && (string.IsNullOrEmpty(Condition.Creater) || k.Creater == Condition.Creater)).Result
                    }).ToList();

                    var dtoList = _mapper.Map<List<OrganizationDto>>(res);

                    return Ok(new ReturnMsg
                    {
                        Data = list,
                        Msg = "获取组织机构列表成功!",
                        Success = true,
                        Total = list.Count(),
                    });
                }
                catch (Exception e)
                {
                    return Ok(new ReturnMsg
                    {
                        Data = null,
                        Msg = "获取组织机构列表失败!",
                        Success = false,
                        Total = 0,
                    });
                }
            }
            else
            {
                return BadRequest();
            }
        }
        #endregion

        #region 获取所有组织机构, 按父子集分开
        /// <summary>
        /// 获取所有组织机构， 按父子集分开
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetAllUserOrganizationByLevel")]
        public async Task<ActionResult> GetAllUserOrganizationByLevel([FromBody]OrganizationCondition Condition)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var list = await _userOrganizationService.Query(x => x.Belong == 0 && x.IsValid && (string.IsNullOrEmpty(Condition.Creater) || x.Creater == Condition.Creater));

                    var droplist = list.ToList().Select(x => new
                    {
                        value = x.Id,
                        label = x.OrganizationName,
                        children = _userOrganizationService.Query(k => k.Belong == x.Id && k.IsValid).Result.Select(z => new
                        {
                            value = z.Id,
                            label = z.OrganizationName
                        })
                    });

                    var dtoList = _mapper.Map<List<OrganizationDropDown>>(droplist);

                    return Ok(new ReturnMsg
                    {
                        Data = dtoList,
                        Msg = "获取层级组织机构列表成功!",
                        Success = true,
                        Total = list.Count(),
                    });
                }
                catch (Exception)
                {
                    return Ok(new ReturnMsg
                    {
                        Data = null,
                        Msg = "获取层级组织机构列表失败!",
                        Success = false,
                        Total = 0,
                    });
                }
            }
            else
            {
                return BadRequest();
            }
        }
        #endregion

        #region 分页获取所有组织机构
        /// <summary>
        /// 分页获取所有组织机构
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetAllUserOrganizationByPage")]
        public async Task<ActionResult> GetAllUserOrganizationByPage([FromBody]OrganizationCondition Condition)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // 获取所有的父级菜单列表
                    var list = await _userOrganizationService.QueryByCondition(x => x.Belong == 0 && x.IsValid && (string.IsNullOrEmpty(Condition.Creater) || x.Creater == Condition.Creater), Condition.IsPage, Condition.PageIndex, Condition.PageSize, x => x.Id, Condition.IsAsc);
                    
                    var res = list.PageData.ToList().Select(x => new
                    {
                        Id = x.Id,
                        Belong = x.Belong,
                        CreateTime = x.CreateTime,
                        DeleteTime = x.DeleteTime,
                        IsValid = x.IsValid,
                        Remark = x.Remark,
                        OrganizationCode = x.OrganizationCode,
                        OrganizationName = x.OrganizationName,
                        Creater = x.Creater,
                        Children = _userOrganizationService.Query(k => k.Belong == x.Id && k.IsValid && (string.IsNullOrEmpty(Condition.Creater) || k.Creater == Condition.Creater)).Result
                    }).ToList();

                    var dtoList = _mapper.Map<List<OrganizationDto>>(res);

                    return Ok(new ReturnMsg
                    {
                        Data = dtoList,
                        Msg = "分页获取组织机构列表成功!",
                        Success = true,
                        Total = list.TotalCount,
                    });
                }
                catch (Exception e)
                {
                    return Ok(new ReturnMsg
                    {
                        Data = null,
                        Msg = "分页获取组织机构列表失败!",
                        Success = false,
                        Total = 0,
                    });
                }
            }
            else
            {
                return BadRequest();
            }
        }
        #endregion

        #region 添加组织机构 更新组织机构 删除组织机构
        /// <summary>
        /// 添加组织机构 更新组织机构 删除组织机构
        /// </summary>
        /// <param name="baseOperation">参数</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Operation")]
        public async Task<ActionResult> Operation([FromBody]BaseOperation<OrganizationDto> baseOperation)
        {
            if (ModelState.IsValid)
            {
                var Entity = _mapper.Map<UserOrganization>(baseOperation.Dto);
                //不知道为啥转换UserOrganization的时候OrganizationCode值为null
                Entity.OrganizationCode = baseOperation.Dto.OrganizationCode;
                bool result = false;

                string msg = "";

                switch (baseOperation.Action)
                {
                    case OperationEnum.add:
                        result = await _userOrganizationService.Add(Entity) > 0;
                        msg = "添加";
                        break;
                    case OperationEnum.update:
                        result = await _userOrganizationService.Update(Entity);
                        msg = "更新";
                        break;
                    case OperationEnum.delete:
                        Entity.IsValid = false;
                        result = await _userOrganizationService.Delete(Entity);
                        msg = "删除";
                        break;
                }
                return Ok(new ReturnMsg
                {
                    Data = result ? baseOperation.Dto : null,
                    Msg = msg + "组织机构" + (result ? "成功" : "失败") + "!",
                    Success = result,
                    Total = result ? 1 : 0,
                });
            }
            else
            {
                return Ok(new ReturnMsg
                {
                    Data = null,
                    Msg = "参数错误!",
                    Success = false,
                    Total = 1,
                });
            }
        }
        #endregion
    }
}